package com.ansion.basedb.storage.secure;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.ansion.basedb.storage.api.BaseKeyValueStorage;
import com.ansion.preference.TurboBasePreference;

public class CipherKeyManager {
    private final BaseKeyValueStorage passwordKvs;

    private static volatile CipherKeyManager inst;

    private CipherKeyManager() {
        if (!TurboBasePreference.mmkvInited) {
            throw new IllegalStateException("you must initMMKV first");
        }
        passwordKvs = new SpStorageImpl(CipherConfig.KeyValueMeta.CIPHER_TABLE_NAME);
    }

    public static CipherKeyManager getInst() {
        if (inst == null) {
            synchronized (CipherKeyManager.class) {
                if (inst == null)
                    inst = new CipherKeyManager();
            }
        }
        return inst;
    }


    public String getPassword(@NonNull String name) {
        String password = passwordKvs.getString(name, null);
        if (TextUtils.isEmpty(password)) {
            String newPwd = CipherProtocol.getRandomStoragePassword();
            passwordKvs.putString(name, newPwd);
            return newPwd;
        }
        return password;
    }

}
